package com.sdhs.file.service.impl;

import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sdhs.common.utils.StringUtils;
import com.sdhs.file.config.MinioConfig;
import com.sdhs.file.domain.SysFileEntity;
import com.sdhs.file.service.ISysFileRyService;
import com.sdhs.file.utils.FileUploadUtils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.log4j.Log4j2;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */

@Service
@Log4j2
public class MinioSysFileServiceImpl implements ISysFileRyService
{
    private MinioConfig minioConfig;

    private MinioClient client;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        // 防止文件重复，生成uuid做文件名
        String id = StringUtils.getUUID();
        String fileType = FilenameUtils.getExtension(fileName);
        SysFileEntity sysFileEntity = null;

        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        IOUtils.closeQuietly(inputStream);
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }
}
